package com.iqik.server;

import com.iqik.common.UserService;
import com.iqik.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class UserServiceImpl implements UserService {
    @Override
    public String sayHello(String msg) {
        return "Hello " + msg;
    }

    public static void startServer(String ip, int port) throws InterruptedException {
        // 1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 2。创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 3。配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                // s设置通道为NIO
                .channel(NioServerSocketChannel.class)
                // 创建channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象设置编码
                        pipeline.addFirst(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        // 自定义一个ChannelHandler添加到管道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });
        // 4。绑定端口
        serverBootstrap.bind(port).sync();
    }
}
